package com.itheima.aop;

import com.itheima.domain.Result;
import com.itheima.domain.pojo.EmpLoginLog;
import com.itheima.domain.pojo.LoginInfo;
import com.itheima.mapper.LoginLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

@Aspect
@Component
@Slf4j
public class LoginLog {
    @Autowired
    private LoginLogMapper loginLogMapper;

    @Around("execution(* com.itheima.controller.LoginController.*(..))")
    public Object loginLog(ProceedingJoinPoint pjp) throws Throwable {
        log.info("方法开始");
        //原始方法的参数
        Object[] args = pjp.getArgs();
        /*//获取登陆的用户名
        String username = (String) args[0];
        //获取登陆密码
        String password = (String) args[1];*/

        //获取登陆的用户名
        String username = null;
        //获取登陆密码
        String password = null;
        if (args.length > 0 && args[0] instanceof Map) {
            Map<String, Object> requestMap = (Map<String, Object>) args[0];
            username = (String) requestMap.get("username");
            password = (String) requestMap.get("password");
        }

        //操作时间
        LocalDateTime loginTime = LocalDateTime.now();
        //方法执行时长
        long startTime = System.currentTimeMillis();
        Object result = null;

        try {
            //原始方法
            result = pjp.proceed();
            return result;
        } finally {
            long endTime = System.currentTimeMillis();
            //原始方法执行时长
            long costTime = endTime - startTime;
            //原始方法是否成功
            Short isSuccess = 0;
            String jwt = null;
            if (result instanceof Result) {
                Result res = (Result) result;
                if (res.getCode() == 1) {
                    isSuccess = 1;
                    //登陆成功还要再获取token
                    Object data = res.getData();
                    /*Map<String, Object> map = (Map<String, Object>) data;
                    jwt = (String) map.get("token");*/
                    if (data instanceof LoginInfo) {
                        // 如果 data 是 LoginInfo 对象
                        LoginInfo loginInfo = (LoginInfo) data;
                        jwt = loginInfo.getToken();  // 假设 LoginInfo 有 getToken() 方法
                    } else {
                        log.warn("未知的 data 类型: {}", data != null ? data.getClass() : "null");
                    }
                }
            } else {
                isSuccess = 0;
            }
            //封装对象
            EmpLoginLog empLoginLog = new EmpLoginLog(null, username, password, loginTime, isSuccess, jwt, costTime);
            //记录日志到数据库
            loginLogMapper.insertLoginLog(empLoginLog);
        }
    }

}
